﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class XemChiTietGioHang : System.Web.UI.Page
{
    private DataSet objShoppingCartDS;
    private DataSet objOrdersDS;

    protected void Page_Load(object sender, EventArgs e)
    {
        // populate the control only on the initial page load
        if (!IsPostBack)
            PopulateControls();
    }
    public void PopulateControls()
    {
        // get the items in the shopping cart
        GioHangBUS objShoppingCart =
            new GioHangBUS(TGDDConfiguration.DbConnectionString);
        try
        {
            objShoppingCartDS = objShoppingCart.GetItemsIntoGioHang(
                AccessGioHang.idGioHang);
            if (objShoppingCartDS.Tables[0].Rows.Count == 0)
            {
                lblTitle.Text = "Giỏ hàng của bạn không chứa sản phẩn nào!";
                grid.Visible = false;
                btnUpdate.Enabled = false;
                btnCheckOut.Enabled = false;
                lblTotalAmount.Text = String.Format("{0:#,##0;Nothing}", 0) + " VNĐ"; ;
            }
            else
            {
                // populate the list with the shopping cart contents
                grid.DataSource = objShoppingCartDS.Tables[0]; ;
                grid.DataBind();
                // setup controls
                lblTitle.Text = "Các sản phẩm hiện có trong giỏ hàng:";
                grid.Visible = true;
                btnUpdate.Enabled = true;
                btnCheckOut.Enabled = true;
                // display the total amount
                objShoppingCart = new GioHangBUS(
                    TGDDConfiguration.DbConnectionString);
                objShoppingCartDS = objShoppingCart.GetTotalAmountGioHang(
                    AccessGioHang.idGioHang);
                DataRow row = objShoppingCartDS.Tables[0].Rows[0];
                decimal amount = decimal.Parse(row["TongTien"].ToString());
                lblTotalAmount.Text = String.Format("{0:#,##0;Nothing}", amount) + " VNĐ"; ;
            }
        }
        catch (System.Exception ex)
        {
            throw new Exception(ex.Message, ex.InnerException);
        }
    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        // Number of rows in the GridView
        int rowsCount = grid.Rows.Count;
        // Will store a row of the GridView
        GridViewRow gridRow;
        // Will reference a quantity TextBox in the GridView
        TextBox quantityTextBox;
        // Variables to store product ID and quantity
        string productId;
        int quantity;
        // Was the update successful?
        bool success = true;
        // Go through the rows of the GridView
        for (int i = 0; i < rowsCount; i++)
        {
            // Get a row
            gridRow = grid.Rows[i];
            // The ID of the product being deleted
            productId = grid.DataKeys[i].Value.ToString();
            // Get the quantity TextBox in the Row
            quantityTextBox = (TextBox)gridRow.FindControl("txtEditQuantity");
            // Get the quantity, guarding against bogus values
            if (Int32.TryParse(quantityTextBox.Text, out quantity))
            {
                if (quantity < 0)
                {
                    lblValidateCheckout.Text = "Vui lòng nhập số hợp lệ";
                    return;
                }
                lblValidateCheckout.Text = "";
                // Update product quantity
                GioHangBUS objShoppingCart = new GioHangBUS(
                    TGDDConfiguration.DbConnectionString);
                GioHangDTO shoppingCartDto = new GioHangDTO();
                shoppingCartDto.Id = AccessGioHang.idGioHang;
                shoppingCartDto.IdSanPham = int.Parse(productId);
                shoppingCartDto.SoLuong = quantity;
                try
                {
                    success = success && objShoppingCart.UpdateItemInGioHang(shoppingCartDto);
                }
                catch (System.Exception ex)
                {
                    throw new Exception(ex.Message, ex.InnerException);
                }
            }
            else
            {
                lblValidateCheckout.Text = "Vui lòng nhập số hợp lệ";
                // if TryParse didn't succeed
                success = false;
            }
            // Display status message
            lblStatus.Text = success ?
              "<br />Giỏ hàng của bạn đã được cập nhật thành công!<br />" :
              "<br />Cập nhật giỏ hàng thất bại, vui lòng kiểm lại giỏ hàng!<br />";
        }
        // Repopulate the control
        PopulateControls();
    }
    protected void grid_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        // Index of the row being deleted
        int rowIndex = e.RowIndex;
        // The ID of the product being deleted
        string productId = grid.DataKeys[rowIndex].Value.ToString();
        // Remove the product from the shopping cart
        GioHangBUS objShoppingCart =
            new GioHangBUS(TGDDConfiguration.DbConnectionString);
        try
        {
            bool success = objShoppingCart.RemoveItemInGioHang(
                AccessGioHang.idGioHang, int.Parse(productId));
            // Display status
            lblStatus.Text = success ? "<br />Sản phẩm đã được lấy ra khỏi giỏ hàng!<br />" :
                              "<br />Có lỗi trong việc lấy sản phẩm ra khỏi giỏ hàng!<br />";
            // Repopulate the control
            PopulateControls();
        }
        catch (System.Exception ex)
        {
            throw new Exception(ex.Message, ex.InnerException);
        }
    }

    // Redirects to the previously visited catalog page 
    // (an alternate to the functionality implemented here is to 
    // Request.UrlReferrer, although that way you have no control over 
    // what pages you forward your visitor back to)
    protected void btnContinueShopping_Click(object sender, EventArgs e)
    {
        // redirect to the last visited catalog page, or to the
        // main page of the catalog
        object page;
        if ((page = Session["LastVisitedCatalogPage"]) != null)
            Response.Redirect(page.ToString());
        else
            Response.Redirect(Request.ApplicationPath);
    }

    // create a new order and redirect to a payment page
    protected void btnCheckOut_Click(object sender, EventArgs e)
    {
        // Store the total amount because the cart 
        // is emptied when creating the order
        // display the total amount
        GioHangBUS objShoppingCart = new GioHangBUS(
            TGDDConfiguration.DbConnectionString);
        objShoppingCartDS = objShoppingCart.GetTotalAmountGioHang(
            AccessGioHang.idGioHang);
        DataRow row = objShoppingCartDS.Tables[0].Rows[0];
        decimal amount = decimal.Parse(row["TongTien"].ToString());
        Response.Redirect("ThanhToan.aspx?sotien=" + amount);
    }
}
